package com.bristua.barcode.job;

import com.bristua.barcode.common.code.Api;
import com.bristua.barcode.common.code.ImagePreProcess;
import com.bristua.barcode.common.code.Util;
import com.bristua.barcode.common.config.VerificationCodeConfig;
import com.bristua.barcode.common.constants.Constants;
import com.bristua.barcode.common.util.DateUtils;
import com.bristua.barcode.common.util.HttpClientUtils;
import com.bristua.barcode.common.util.JsonUtil;
import com.bristua.barcode.common.util.MD5Util;
import com.bristua.barcode.job.bo.StandardOrder;
import com.bristua.barcode.order.model.bo.LakalaOrder;
import com.bristua.barcode.supplier.model.TQrCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/9/10.
 */
@Service
public class GetLakalaOrderImpl implements IGetOrder {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VerificationCodeConfig verificationCodeConfig;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public List<StandardOrder> getOrder(String orderAmt, String tranStartDate, String systemNo, TQrCode tQrCode) {
        List<LakalaOrder> lakalaOrders = getLakalaOrder(tQrCode.getUserName(), tQrCode.getPassword(), orderAmt, tranStartDate, systemNo);
        if (lakalaOrders != null && lakalaOrders.size() > 0) {
            List<StandardOrder> standardOrderList = new ArrayList<>();
            for (LakalaOrder lakalaOrder : lakalaOrders) {
                StandardOrder standardOrder = new StandardOrder();
                standardOrder.setPayAmt((new BigDecimal(lakalaOrder.getTranAmount()).multiply(new BigDecimal(100))).longValue());
                String tranStatus = lakalaOrder.getTranStatus();
                switch (tranStatus) {
                    case "S":
                        standardOrder.setPayStatus(Constants.PAY_SUCCESS);
                        break;
                    case "P":
                        standardOrder.setPayStatus(Constants.WAIT_PAY);
                        break;
                    default:
                        standardOrder.setPayStatus(Constants.PAY_FAIL);
                        break;
                }
                standardOrder.setPayTime(lakalaOrder.getTranDate() + " " + lakalaOrder.getTranTime());
                standardOrder.setPayType(lakalaOrder.getDebitInfoName().contains("微信") ? "1" : "2");
                standardOrder.setSystemNo(lakalaOrder.getSystemReferNo());
                standardOrderList.add(standardOrder);
            }
            return standardOrderList;
        }
        return null;
    }

    private String getEndTime(String startTime) {
        try {
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = time.parse(startTime);
            Date afterDate = new Date(d.getTime() + 200000);//后3分钟
            return time.format(afterDate);
        } catch (Exception ex) {
            logger.error("时间解析异常", ex);
        }
        return null;
    }

    private List<LakalaOrder> getLakalaOrder(String username, String password, String orderAmt, String tranStartDate, String systemNo) {
        String cookie = String.valueOf(redisTemplate.opsForValue().get(MD5Util.Bit32(username + password)));
        if (StringUtils.isEmpty(cookie) || "null".equals(cookie)) {
            cookie = login(username, password);
        }
        String[] split = tranStartDate.split(" ");

        String endTime = getEndTime(tranStartDate);
        String[] split1 = endTime.split(" ");

        Map orders = new HashMap();
        if (StringUtils.isEmpty(systemNo)) {
            orders.put("startTranTime", split[1]);
            orders.put("endTranTime", split1[1]);
            String date = DateUtils.getDate();
            orders.put("tranStartDate", split[0]);
            orders.put("tranEndDate", split1[0]);
            orders.put("tranType", "P09");
            orders.put("tranStatus", "");
            orders.put("tranAmtEnd", orderAmt);
            orders.put("tranAmtStart", orderAmt);
            orders.put("page", 1);
            orders.put("size", 120);
        } else {
            orders.put("systemReferNo", systemNo);
            orders.put("page", 1);
            orders.put("size", 20);
        }


        String data = HttpClientUtils.postJSON("https://s.lakala.com/api/v1/transaction/queryRealTransaction", JsonUtil.toJson(orders), cookie);
//        System.out.println("账号:17355401106,数据:" + data);//data为空时或为null说明session失效
        if (StringUtils.isEmpty(data)) {
            login(username, password);
            getLakalaOrder(username, password, orderAmt, tranStartDate, systemNo);
        }
        Map map = JsonUtil.json2Map(data);

        if (map.get("data") != null && map.get("data") instanceof List) {
            return (List<LakalaOrder>) map.get("data");
        }

        return null;
    }


    private Map<String, Object> getCode() {
        Api api = new Api();
        api.Init(verificationCodeConfig.getAppId(), verificationCodeConfig.getAppKey(), verificationCodeConfig.getPdId(), verificationCodeConfig.getPdKey());
        Map<String, Object> map = ImagePreProcess.downloadImage();
        try {
            Util.HttpResp predict = api.PredictFromFile("30500", map.get("fileName").toString());
            map.put("code", predict.pred_resl);
        } catch (Exception ex) {
            logger.error("解析验证码异常", ex);
        }
        return map;
    }

    private String login(String username, String password) {
        Map<String, Object> code = getCode();
        Map params = new HashMap<>();
        params.put("name", username);
        params.put("password", password);
        params.put("proxyMerchant", "0");
        params.put("captcha", String.valueOf(code.get("code")));
        String json = JsonUtil.toJson(params);
        String cookie = String.valueOf(code.get("cookie"));
        HttpClientUtils.postJSON("https://s.lakala.com/api/v1/login", json, cookie);
        redisTemplate.opsForValue().set(MD5Util.Bit32(username + password), cookie);
        return cookie;
    }
}
